/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-6-17 下午4:26:43
 */
package com.absir.android.orm;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.absir.bean.basis.Configure;
import com.absir.bean.inject.value.Inject;
import com.absir.bean.inject.value.InjectType;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

/**
 * @author absir
 * 
 */
@Configure
public class DaoHelper extends OrmLiteSqliteOpenHelper {

	/** TAG */
	private static final String TAG = DaoHelper.class.getSimpleName();

	/** Dao_Helper */
	private static IDaoHelper Dao_Helper;

	/** Database_Version */
	private static int Database_Version = 1;

	/**
	 * @param daoHelper
	 */
	@Inject(type = InjectType.Selectable)
	private static void setDaoHelper(IDaoHelper daoHelper) {
		Dao_Helper = daoHelper;
		Database_Version = Dao_Helper.getVersion();
	}

	/**
	 * @param context
	 * @param dataBaseName
	 */
	public DaoHelper(Context context, String dataBaseName) {
		super(context, dataBaseName, null, Database_Version);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper#onCreate(android
	 * .database.sqlite.SQLiteDatabase,
	 * com.j256.ormlite.support.ConnectionSource)
	 */
	@Override
	public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onCreate:" + database.getVersion());
		for (Class<?> tableType : DaoFactory.Table_Types) {
			try {
				TableUtils.createTable(connectionSource, tableType);
			} catch (Exception e) {
				Log.e(TAG, "create table " + tableType + " error!", e);
			}
		}

		if (Dao_Helper != null) {
			Dao_Helper.onCreate(database, connectionSource);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper#onUpgrade(android
	 * .database.sqlite.SQLiteDatabase,
	 * com.j256.ormlite.support.ConnectionSource, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		if (Dao_Helper != null) {
			Dao_Helper.onUpgrade(database, connectionSource, oldVersion, newVersion);
		}
	}
}
